package com.lyf.shop.dao.Impl;

import com.lyf.shop.dao.AddressDao;
import com.lyf.shop.entity.Address;
import com.lyf.shop.util.DataBaseUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    private QueryRunner qr = new QueryRunner();
    @Override
    public List<Address> getAddressByUid(int uid) throws SQLException {
        return qr.query(DataBaseUtil.getConnection(),
                "select * from address where uid=? order by astate desc",new BeanListHandler<>(Address.class),uid);
    }

    @Override
    public int insertAddr(Address address) throws SQLException{
        return qr.update(DataBaseUtil.getConnection(),
                "insert into address values (default ,?,?,?,?,?)",
                address.getUid(),address.getAname(),address.getAphone(),address.getAdetail(),address.getAstate());
    }

    @Override
    public int delAddr(int aid) throws SQLException {
        return qr.update(DataBaseUtil.getConnection(),
                "delete from address where aid=?",aid);
    }

    @Override
    public int updateAddr(Address address) throws SQLException {
        return qr.update(DataBaseUtil.getConnection(),
                "update address set aname=?,aphone=?,adetail=?,astate=? where aid=? ",
                address.getAname(),address.getAphone(),address.getAdetail(),address.getAstate(),address.getAid());
    }

    @Override
    public int changeAddrToDefault(int aid) throws SQLException{
        return qr.update(DataBaseUtil.getConnection(),
                "update address set astate=1 where aid=? ",aid);
    }

    @Override
    public int changeAddrToCommons(int aid, int uid) throws SQLException{
        return qr.update(DataBaseUtil.getConnection(),
                "update address  set astate=0 where aid!=? and uid=?", aid,uid);
    }
}
